const Router = require('koa-router');
const mongoose = require('mongoose');
const router = new Router();

router.get('/', async(ctx) => {
  ctx.body = '<h1>这是用户操作首页</h1>';
})

router.post('/register', async(ctx) => {
  const User = mongoose.model('user');    // 在service/database/schema/User.js中发布了user模型
  let newUser = new User(ctx.request.body);
  await newUser.save().then(() => {
    //成功返回code=200，并返回成功信息
    ctx.response.body={code:0, message:'注册成功'};
  }).catch((err) => {
    ctx.response.body={code:500, message:err};
  });
})

router.post('/login', async(ctx) => {
  let loginUser = ctx.request.body;
  let userName = loginUser.userName;
  let password = loginUser.password;
  const User = mongoose.model('user');
  await User.findOne({userName}).exec().then(async(result) => {
    if (result) {   //当用户名存在时
      let newUser = new User();
      await newUser.comparePassword(password, result.password)
        .then(isMatch => {    // 密码匹配正确时
          ctx.response.body = { code:0, message:isMatch };
        })
        .catch(error => {   // 密码匹配错误时
          ctx.response.body = { code:0, message:error };
        })
    } else {    //当用户名不存在时
      ctx.response.body={ code:0, message:'用户名不存在'}
    }
  }).catch(err => {   // 查询出错时的返回
    ctx.response.body={ code:500, message:error  }
  })
})

module.exports = router;
